<template>
  <div>
    <scroller :show-scrollbar="false">
      <div class="td-row">
        <text class="td-text text-muted">批次号</text>
        <text class="td-text text-muted">日龄</text>
        <text class="td-text text-muted">入栏数</text>
        <text class="td-text text-muted">出栏数</text>
        <text class="td-text text-muted">存活率</text>
      </div>

      <text v-if="!columns.length"
            class="empty-text">无当前入栏信息</text>

      <div v-else>
        <div v-for="(column, index) in columns"
             :key="index"
             :class="['td-row', index === columnIndex && 'td-row-active']"
             @click="onColumnSelect(index)">
          <text class="td-text">{{column.enter_batch_no}}</text>
          <text class="td-text">{{column.day_age}}</text>
          <text class="td-text">{{column.chick_amount}}</text>
          <text class="td-text">{{column.out_chick_amount || '-'}}</text>
          <text class="td-text">{{column.sur_rate || '-'}}</text>
        </div>
      </div>

      <div class="house-title">
        <text class="icon text-primary mr-1">&#xe87b;</text>
        <text class="text-primary mr-1">鸡舍信息</text>
        <text class="small text-muted"
              v-if="columnIndex > -1">批次: {{columnSelected.enter_batch_no}}, 产品: {{columnSelected.product_name || '-'}}</text>
      </div>
      <!-- <vm-title title="鸡舍信息"
                :marginTop="true"
                :show-arrow="false"></vm-title> -->

      <div class="house-wrap">
        <div class="house-bottom"></div>
        <scroller class="house-scroller"
                  scroll-direction="horizontal">
          <div v-for="(house, index) in houseList"
               :key="index"
               :class="[index === houseIndex ? 'house-active' : 'house']"
               @click="onSelectHouse(house, index)">
            <div :class="[index === houseIndex ? 'house-inner-active' : 'house-inner']">
              <text class="house-no">{{house.house_no}}栋</text>
              <text :class="['house-status', 'house-status-all', house.houseStyle]"
                    v-if="columnIndex === -1">{{house.houseStatus}}</text>
              <div v-else>
                <text class="house-status">{{house.current_amount}}羽</text>
                <text class="house-status">{{house.current_day_age || '-'}}天</text>
                <text class="house-status">{{house.sur_rate}}</text>
              </div>
            </div>
          </div>
        </scroller>
        <text class="house-next icon"
              v-if="houses.length >= 4">&#xe605;</text>
      </div>

      <div class="house-log">
        <div class="log-tab">
          <text v-for="(tab, index) in logTabs"
                :key="index"
                class="log-tab-text"
                :class="[
                logTabIndex === index ? 'log-tab-text-active' : 'log-tab-text-inactive',
                index === 0 && 'ml-2',
                index === tabLen - 1 && 'mr-2'
                ]"
                @click="selectLogTab(index)">{{tab}}</text>
        </div>

        <text v-if="!columns.length"
              class="log-content empty-text">请先入栏</text>

        <text v-else-if="!houses.length"
              class="log-content empty-text">无入舍信息</text>

        <div class="container"
             v-else>
          <div ref="log-container"
               class="log-container"
               :style="{width: tabLen * logContentWidth}">
            <div class="log-content">
              <div class="flex-row mb-2">
                <text class="small flex">时间：{{currentLogDateStr}}</text>
                <text :class="[
              'log-status',
              hasCurrentBaseLog ? 'log-status-success': 'log-status-warning'
              ]">{{hasCurrentBaseLog ? '已填写' : '未填写'}}</text>
              </div>

              <div class="flex-row mb-2">
                <div class="flex-row flex mr-2">
                  <text class="label-text">死鸡数</text>
                  <input type="number"
                         @keyboard="onKeyboard"
                         @focus="onInputFocus(baseLog.die_num)"
                         @blur="saveBaseLog('die_num')"
                         placeholder="请填写"
                         v-model="baseLog.die_num"
                         class="input" />
                  <text class="unit-text">羽</text>
                </div>
                <div class="flex-row flex">
                  <text class="label-text">淘汰数</text>
                  <input type="number"
                         placeholder="请填写"
                         @focus="onInputFocus(baseLog.eli_num)"
                         @blur="saveBaseLog('eli_num')"
                         v-model="baseLog.eli_num"
                         class="input" />
                  <text class="unit-text">羽</text>
                </div>
              </div>

              <div class="flex-row mb-2">
                <div class="flex-row flex mr-2"
                     @click="showForage">
                  <text class="label-text">投料类</text>
                  <text :class="[
                'select',
                 baseLog.feed_product_id ? 'select-text' : 'select-placeholder'
                 ]">{{baseLog.feed_product_name || '选择投料'}}</text>
                  <text class="icon unit-text">&#xe69b;</text>
                </div>
                <div class="flex-row flex">
                  <text class="label-text">投料数</text>
                  <input type="number"
                         placeholder="请填写"
                         @blur="saveBaseLog('feed_dosage')"
                         v-model="baseLog.feed_dosage"
                         class="input" />
                  <text class="unit-text">千克</text>
                </div>
              </div>

              <div class="flex-row mb-2"
                   v-if="baseLog.hasEgg">
                <div class="flex-row flex mr-2">
                  <text class="label-text">产蛋数</text>
                  <input type="number"
                         placeholder="请填写"
                         @blur="saveBaseLog('egg_num')"
                         v-model="baseLog.egg_num"
                         class="input" />
                  <text class="unit-text">枚</text>
                </div>
                <div class="flex-row flex">
                  <text class="label-text">异蛋数</text>
                  <input type="number"
                         placeholder="请填写"
                         @blur="saveBaseLog('ex_egg_num')"
                         v-model="baseLog.ex_egg_num"
                         class="input" />
                  <text class="unit-text">枚</text>
                </div>
              </div>

            </div>

            <div class="log-content">
              <div class="flex-row mb-2">
                <text class="small flex">时间：{{currentLogDateStr}}</text>
                <text :class="[
                      'log-status',
                      hasCurrentDrugAndImm ? 'log-status-success': 'log-status-warning'
                      ]">{{hasCurrentDrugAndImm ? '已填写' : '未填写'}}</text>
              </div>

              <div class="flex-row mb-2">
                <text class="label-text">免疫类</text>
                <div class="log-table-wrap"
                     @click="showVaccine">
                  <text class="small text-muted icon"
                        v-if="!baseLog.logImm.length">选择免疫类 &#xe69b;</text>
                  <div class="flex-row"
                       style="margin-bottom: 5px;"
                       v-for="(drug, index) in baseLog.logImm"
                       :key="index">
                    <text class="small flex">{{drug.name}}</text>
                    <div class="flex flex-row">
                      <text class="small text-muted">用量: </text>
                      <text class="small">{{drug.amount}}{{drug.unit}}</text>
                    </div>
                  </div>
                </div>
              </div>

              <div class="flex-row mb-2">
                <text class="label-text">用药类</text>
                <div class="log-table-wrap"
                     @click="showDrug">
                  <text class="small text-muted icon"
                        v-if="!baseLog.logDrug.length">选择用药类 &#xe69b;</text>
                  <div class="flex-row"
                       style="margin-bottom: 5px;"
                       v-for="(drug, index) in baseLog.logDrug"
                       :key="index">
                    <text class="small flex">{{drug.name}}</text>
                    <div class="flex flex-row">
                      <text class="small text-muted">用量: </text>
                      <text class="small">{{drug.amount}}{{drug.unit}}</text>
                    </div>
                  </div>
                </div>
              </div>

            </div>

            <div class="log-content">
              <div class="flex-row mb-2">
                <text class="small flex">时间：{{currentLogDateStr}}</text>
                <text :class="[
              'log-status',
              hasCurrentBaseLogTemperature ? 'log-status-success': 'log-status-warning'
              ]">{{hasCurrentBaseLogTemperature ? '已填写' : '未填写'}}</text>
              </div>

              <div class="flex-row mb-2">
                <div class="flex-row flex mr-2">
                  <text class="label-text">均温度</text>
                  <input type="number"
                         placeholder="请填写"
                         @blur="saveBaseLog('temperature')"
                         v-model="baseLog.temperature"
                         class="input" />
                  <text class="unit-text">℃</text>
                </div>
                <div class="flex-row flex"></div>
              </div>

              <div class="flex-row mb-2">
                <div class="flex-row flex mr-2">
                  <text class="label-text">均湿度</text>
                  <input type="number"
                         placeholder="请填写"
                         @blur="saveBaseLog('humidity')"
                         v-model="baseLog.humidity"
                         class="input" />
                  <text class="unit-text">%</text>
                </div>
                <div class="flex-row flex"></div>
              </div>

            </div>

            <div class="log-content">
              <div class="flex-row mb-2">
                <text class="small flex">时间：{{currentLogDateStr}}</text>
                <text :class="[
              'log-status',
              hasCurrentBaseLogAvgWeight ? 'log-status-success': 'log-status-warning'
              ]">{{hasCurrentBaseLogAvgWeight ? '已填写' : '未填写'}}</text>
              </div>

              <div class="flex-row mb-2">
                <div class="flex-row flex mr-2">
                  <text class="label-text">鸡均重</text>
                  <input type="number"
                         placeholder="请填写"
                         @blur="saveBaseLog('avg_weight')"
                         v-model="baseLog.avg_weight"
                         class="input" />
                  <text class="unit-text">千克</text>
                </div>
                <div class="flex-row flex"></div>
              </div>

              <div class="flex-row mb-2"
                   v-if="baseLog.hasEgg">
                <div class="flex-row flex mr-2">
                  <text class="label-text">蛋均重</text>
                  <input type="number"
                         placeholder="请填写"
                         @blur="saveBaseLog('egg_avg_weight')"
                         v-model="baseLog.egg_avg_weight"
                         class="input" />
                  <text class="unit-text">克</text>
                </div>
                <div class="flex-row flex"></div>
              </div>

            </div>
          </div>

        </div>

      </div>

      <div class="flex-row p-2 bg-white border-bottom log-border-head">
        <text class="flex">历史信息</text>
        <div class="flex-row"
             @click="goHistory">
          <text class="small text-muted">查看历史批次</text>
          <text class="text-muted icon">&#xe6a2;</text>
        </div>
      </div>

      <div class="container">
        <div class="tab-container"
             ref="tab-history"
             :style="{width: tabLen * logContentWidth}">
          <div class="tab-content">
            <text v-if="!logBaseSelected.length"
                  class="empty-text">无历史信息</text>
            <div v-else>
              <div class="td-row">
                <text class="td-serial text-muted">栋号</text>
                <text class="td-text text-muted">时间</text>
                <text class="td-text text-muted">死鸡数</text>
                <text class="td-text text-muted">淘汰数</text>
                <text class="td-text text-muted">投料类</text>
                <text class="td-text text-muted"
                      v-if="baseLog.hasEgg">产蛋数</text>
                <text class="td-text text-muted"
                      v-if="baseLog.hasEgg">异蛋数</text>
              </div>
              <div class="td-row"
                   v-for="(item, index) in logBaseSelected"
                   :key="index">
                <text class="td-serial">{{item.house_no}}</text>
                <text class="td-text">{{item.log_time}}</text>
                <text class="td-text">{{item.die_num}}</text>
                <text class="td-text">{{item.eli_num || '-'}}</text>
                <text class="td-text">{{item.feed_product_name || '-'}}</text>
                <text class="td-text"
                      v-if="baseLog.hasEgg">{{item.egg_num || '-'}}</text>
                <text class="td-text"
                      v-if="baseLog.hasEgg">{{item.ex_egg_num || '-'}}</text>
              </div>
            </div>
          </div>

          <div class="tab-content">
            <text v-if="!logBaseSelected.length"
                  class="empty-text">无历史信息</text>
            <div v-else>
              <div class="td-row">
                <text class="td-serial text-muted">栋号</text>
                <text class="td-text text-muted">时间</text>
                <text class="td-text text-muted">免疫类</text>
                <text class="td-text text-muted">免疫用量</text>
                <text class="td-text text-muted">用药类</text>
                <text class="td-text text-muted">用药用量</text>
              </div>
              <div class="td-row"
                   v-for="(item, index) in logBaseSelected"
                   :key="index">
                <text class="td-serial">{{item.house_no}}</text>
                <text class="td-text">{{item.log_time}}</text>
                <text class="td-text">{{item.imm_product_name}}</text>
                <text class="td-text">{{item.imm_dosage || '-'}}</text>
                <text class="td-text">{{item.drug_product_name || '-'}}</text>
                <text class="td-text">{{item.drug_product_amount || '-'}}</text>
              </div>
            </div>
          </div>

          <div class="tab-content">
            <text v-if="!logBaseSelected.length"
                  class="empty-text">无历史信息</text>
            <div v-else>
              <div class="td-row">
                <text class="td-serial text-muted">栋号</text>
                <text class="td-text text-muted">时间</text>
                <text class="td-text text-muted">均温度</text>
                <text class="td-text text-muted">均湿度</text>
              </div>
              <div class="td-row"
                   v-for="(item, index) in logBaseSelected"
                   :key="index">
                <text class="td-serial">{{item.house_no}}</text>
                <text class="td-text">{{item.log_time}}</text>
                <text class="td-text">{{item.temperature}}</text>
                <text class="td-text">{{item.humidity || '-'}}</text>
              </div>
            </div>
          </div>

          <div class="tab-content">
            <text v-if="!logBaseSelected.length"
                  class="empty-text">无历史信息</text>
            <div v-else>
              <div class="td-row">
                <text class="td-serial text-muted">栋号</text>
                <text class="td-text text-muted">时间</text>
                <text class="td-text text-muted">鸡均重(kg)</text>
                <text class="td-text text-muted"
                      v-if="baseLog.hasEgg">蛋均重(g)</text>
              </div>
              <div class="td-row"
                   v-for="(item, index) in logBaseSelected"
                   :key="index">
                <text class="td-serial">{{item.house_no}}</text>
                <text class="td-text">{{item.log_time}}</text>
                <text class="td-text">{{item.avg_weight}}</text>
                <text class="td-text"
                      v-if="baseLog.hasEgg">{{item.egg_avg_weight || '-'}}</text>
              </div>
            </div>
          </div>
        </div>
      </div>

    </scroller>

    <vm-mask height="600"
             width="560"
             :show-close="true"
             :show.sync="forageVisible">
      <text class="p-3 border-bottom text-muted">选择投料类</text>
      <scroller :show-scrollbar="false">
        <div v-for="(item, index) in forages"
             :key="index"
             class="list-text flex-row"
             @click="onSelectForage(item, index)">
          <text :class="['flex', forageIndex === index && 'list-text-active']">{{item.goods_name}}</text>
          <text class="small text-muted">库存:{{item.store_amount}}</text>
        </div>
      </scroller>
    </vm-mask>

    <wxc-popup :show="vaccineVisible"
               ref="vaccinePopup"
               @wxcPopupOverlayClicked="vaccineBeforeClose"
               pos="bottom"
               :height="700">
      <text class="p-2 text border-bottom icon">&#xed55; 选择免疫类并填写用量</text>
      <div class="p-3 align-center"
           v-if="!vaccines.length">
        <text class="p-3 text-muted text-center">库存中没有疫苗</text>
        <text class="btn"
              @click="hideVaccine">确定</text>
      </div>

      <div class="flex"
           v-else>
        <div class="td-row">
          <text class="td-serial text-muted">选择</text>
          <text class="td-text text-muted">疫苗名称</text>
          <text class="td-text text-muted">规格</text>
          <text class="td-text text-muted">数量</text>
        </div>
        <scroller :show-scrollbar="false">
          <div class="flex-row p-1"
               v-for="(item, index) in vaccines"
               :key="index"
               @click="toggleVaccine(item, index)">
            <div class="td-serial align-center">
              <text v-if="item.selected"
                    class="icon text-primary">&#xebf1;</text>
              <text v-else
                    class="icon text-muted">&#xebf0;</text>
            </div>
            <text class="td-text">{{item.goods_name}}</text>
            <text class="td-text">{{item.spec_name || '-'}}</text>
            <div class="flex flex-row">
              <input type="number"
                     :placeholder="`库存${item.store_amount}`"
                     v-model="item.useAmount"
                     @blur="onVaccineBlur(item, index)"
                     class="input" />
              <text class="unit-text">{{item.spec_unit || '-'}}</text>
            </div>
          </div>
        </scroller>
        <div class="flex-row popup-btns">
          <div class="popup-btn-border">
            <div class="flex popup-btn popup-btn-dismiss"
                 @click="hideVaccine">
              <text class="popup-btn-text">取消</text>
            </div>
            <div class="flex popup-btn popup-btn-confirm"
                 @click="onVaccineSubmit">
              <text class="popup-btn-text text-white">确认</text>
            </div>
          </div>
        </div>
      </div>
    </wxc-popup>

    <wxc-popup :show="drugVisible"
               ref="drugPopup"
               @wxcPopupOverlayClicked="drugBeforeClose"
               pos="bottom"
               :height="700">
      <text class="p-2 text border-bottom icon">&#xedb4; 选择用药类并填写用量</text>
      <div class="p-3 align-center"
           v-if="!drugs.length">
        <text class="p-3 text-muted text-center">库存中没有药品</text>
        <text class="btn"
              @click="hideDrug">确定</text>
      </div>

      <div class="flex"
           v-else>
        <div class="td-row">
          <text class="td-serial text-muted">选择</text>
          <text class="td-text text-muted">药品名称</text>
          <text class="td-text text-muted">规格</text>
          <text class="td-text text-muted">数量</text>
        </div>
        <scroller :show-scrollbar="false">
          <div class="flex-row p-1"
               v-for="(item, index) in drugs"
               :key="index"
               @click="toggleDrug(item, index)">
            <div class="td-serial align-center">
              <text v-if="item.selected"
                    class="icon text-primary">&#xebf1;</text>
              <text v-else
                    class="icon text-muted">&#xebf0;</text>
            </div>
            <text class="td-text">{{item.goods_name}}</text>
            <text class="td-text">{{item.spec_name || '-'}}</text>
            <div class="flex flex-row">
              <input type="number"
                     :placeholder="`库存${item.store_amount}`"
                     v-model="item.useAmount"
                     @blur="onDrugBlur(item, index)"
                     class="input" />
              <text class="unit-text">{{item.spec_unit || '-'}}</text>
            </div>
          </div>
        </scroller>
        <div class="flex-row popup-btns">
          <div class="popup-btn-border">
            <div class="flex popup-btn popup-btn-dismiss"
                 @click="hideDrug">
              <text class="popup-btn-text">取消</text>
            </div>
            <div class="flex popup-btn popup-btn-confirm"
                 @click="onDrugSubmit">
              <text class="popup-btn-text text-white">确认</text>
            </div>
          </div>
        </div>
      </div>
    </wxc-popup>

  </div>
</template>
<script>
import VmTitle from '../../components/vm-title.vue'
import VmMask from '../../components/vm-mask.vue'
import { WxcPopup } from 'weex-ui'
import {
  STORAGE_FARM
} from '../../plugins/constant'
import {
  enumHouseStatus,
  CATEGORY_EGG_CHICK,
  CATEGORY_FORAGE,
  CATEGORY_VACCINE,
  CATEGORY_DRUG
} from '../../plugins/enumChick'
const animation = weex.requireModule('animation')
const enumHouseStyle = {
  1: 'text-warning',
  2: 'text-info',
  3: 'text-success'
}
const logDateFormat = 'yyyy-MM-dd'

export default {
  components: { VmTitle, VmMask, WxcPopup },
  props: {},
  data() {
    return {
      // 当前批次
      columns: [],
      columnIndex: -1,
      // 鸡舍
      houseIndex: -1,
      allHouses: [],
      // 日志
      logContentWidth: 750,
      logTabs: ['日常管理', '免疫用药', '温度湿度', '均重填写'],
      logTabIndex: 0,
      baseLog: {
        die_num: '',
        eli_num: '',
        feed_product_id: '',
        feed_product_name: '',
        feed_dosage: '',
        egg_num: '',
        ex_egg_num: '',
        avg_weight: '',
        egg_avg_weight: '',
        temperature: '',
        humidity: '',
        logDrug: [],
        logImm: [],
        hasEgg: false
      },
      currentLogDateStr: '',
      currentBaseLog: {},
      test: '',
      // 投料类
      forageVisible: false,
      forageIndex: -1,
      forages: [],
      //免疫类
      vaccines: [],
      vaccineVisible: false,
      // 用药类
      drugs: [],
      drugVisible: false,
      //
      valueBefore: ''
    }
  },
  computed: {
    tabLen() {
      return this.logTabs.length
    },
    columnSelected() {
      return this.columnIndex > -1 && this.columnIndex < this.columns.length ? this.columns[this.columnIndex] : {}
    },
    houses() {
      return this.columnSelected.houses || []
    },
    houseList() {
      return this.houses.length ? this.houses : this.allHouses
    },
    valideHouseIndex() {
      return this.houseIndex > -1 && this.houseIndex < this.houses.length
    },
    houseSelected() {
      return this.valideHouseIndex ? this.houses[this.houseIndex] : {}
    },
    logBaseSelected() {
      return this.houseSelected.logBase || []
    },
    isEggChick() {
      const cateId = this.columnSelected.output_product_category
      return cateId ? cateId.indexOf(CATEGORY_EGG_CHICK) > -1 : false
    },
    hasCurrentBaseLog() {
      return this.currentBaseLog.base_produce_log_id && (
        this.currentBaseLog.die_num ||
        this.currentBaseLog.eli_num ||
        this.currentBaseLog.feed_product_id ||
        this.currentBaseLog.feed_dosage ||
        this.currentBaseLog.egg_num ||
        this.currentBaseLog.ex_egg_num
      )
    },
    hasCurrentBaseLogTemperature() {
      return this.currentBaseLog.base_produce_log_id && (
        this.currentBaseLog.temperature ||
        this.currentBaseLog.humidity
      )
    },
    hasCurrentBaseLogAvgWeight() {
      return this.currentBaseLog.base_produce_log_id && (
        this.currentBaseLog.avg_weight ||
        this.currentBaseLog.egg_avg_weight
      )
    },
    hasCurrentDrugAndImm() {
      return this.currentBaseLog.base_produce_log_id && (
        this.currentBaseLog.drug_product_id ||
        this.currentBaseLog.imm_product_id
      )
    }
  },
  watch: {},
  eros: {
    beforeBackAppear(params) {
      if (params && params.type === 1) {
        this.getColumn()
      }
    }
  },
  created() {
    this.getFarm()
  },
  methods: {
    getFarm() {
      this.farm = this.$storage.getSync(STORAGE_FARM) || {}
      if (this.farm.id) {
        this.getColumn()
        this.getStore()
      } else {
        this.$notice.toast({ message: '没有鸡场信息' })
        this.$router.setBackParams({ type: 1 })
      }

      this.$navigator.setRightItem({
        text: '入栏'
      }, this.goChickin)
    },
    getColumn() {
      this.$notice.loading.show()
      this.$api.getData({
        server: 'agr_chain',
        table: 'chick_column_view',
        params: {
          'supplier_id.eq': this.farm.id,
          'column_status.eq': 1
        }
      }).then(res => {
        const data = res || []
        this.columns = data.map(item => {
          item.houseFetch = false
          item.houses = []
          return item
        })
        if (data.length) {
          this.columnIndex = 0
          this.getHouseEnter()
        } else {
          this.getChickHouse()
        }
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        this.$notice.loading.hide()
      })
    },
    onColumnSelect(index) {
      this.columnIndex = index
      this.getHouseEnter()
    },
    getChickHouse() {
      this.$api.getData({
        server: 'agr_chain',
        table: 'chick_house',
        params: {
          'supplier_id.eq': this.farm.id
        },
        order: {
          house_no: 'asc'
        }
      }).then(res => {
        this.allHouses = (res || []).map(item => {
          item.houseStatus = enumHouseStatus[item.house_status] || ''
          item.houseStyle = enumHouseStyle[item.house_status] || ''
          return item
        })
      }).catch(err => {
        console.log(err)
      })
    },
    getHouseEnter(isForce = false) {
      if (this.columnSelected.houseFetch && !isForce) {
        this.setLogs(this.houseSelected.currentLog)
        return
      }
      this.$api.getData({
        server: 'agr_chain',
        table: 'chick_house_enter_view',
        params: {
          'chick_column_id.eq': this.columnSelected.chick_column_id
        },
        order: {
          house_no: 'asc'
        }
      }).then(res => {
        this.columnSelected.houseFetch = true
        const data = res || []
        this.columnSelected.houses = data.map(item => {
          const currentDayAge = +item.current_day_age || 0
          item.current_amount = item.current_amount
          item.current_day_age = currentDayAge
          item.sur_rate = `${Math.round((+item.sur_rate || 0) * 10000) / 100}%`
          item.logFetch = false
          item.currentLog = {}
          item.logBase = []
          item.logDrug = []
          item.logImm = []
          item.hasEgg = this.isEggChick && currentDayAge >= 120
          return item
        })
        if (data.length) {
          this.houseIndex = this.valideHouseIndex ? this.houseIndex : 0
          this.getBaseLog(isForce)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    getBaseLog(isForce = false) {
      if (this.houseSelected.logFetch && !isForce) {
        this.setLogs(this.houseSelected.currentLog)
        return
      }
      this.$api.getData({
        server: 'agr_chain',
        table: 'base_produce_log_view',
        params: {
          'chick_house_enter_id.eq': this.houseSelected.chick_house_enter_id,
          'log_time.gt': this.$utils.dateFormat(new Date(+new Date() - 8.64e7 * 7), 'yyyy-MM-dd')
        },
        order: {
          log_time: 'desc'
        }
      }).then(res => {
        this.houseSelected.logFetch = true
        const data = res || []
        this.houseSelected.logBase = data.map(item => {
          item.logDrug = []
          if (item.drug_product_id) {
            const drugIds = this.getSplit(item.drug_id)
            // const drugProductIds = this.getSplit(item.drug_product_id)
            const drugNames = this.getSplit(item.drug_product_name)
            const drugUnits = this.getSplit(item.drug_product_unit)
            const drugAmounts = this.getSplit(item.drug_product_amount)
            const drugSpecs = this.getSplit(item.drug_product_spec_id)
            const len = drugIds.length
            if (len <= drugNames.length &&
              // len <= drugProductIds.length &&
              len <= drugUnits.length &&
              len <= drugAmounts.length &&
              len <= drugSpecs.length
            ) {
              for (let i = 0; i < drugIds.length; i++) {
                item.logDrug.push({
                  id: drugIds[i],
                  // productId: drugIds[i],
                  name: drugNames[i],
                  unit: drugUnits[i],
                  amount: drugAmounts[i],
                  spec: drugSpecs[i]
                })
              }
            }
          }
          item.logImm = []
          if (item.imm_product_id) {
            const immIds = this.getSplit(item.imm_id)
            // const immProductIds = this.getSplit(item.imm_product_id)
            const immNames = this.getSplit(item.imm_product_name)
            const immUnits = this.getSplit(item.imm_product_unit)
            const immAmounts = this.getSplit(item.imm_dosage)
            const immSpecs = this.getSplit(item.imm_product_spec_id)
            const len = immIds.length
            if (len <= immNames.length &&
              // len <= immProductIds.length &&
              len <= immUnits.length &&
              len <= immAmounts.length &&
              len <= immSpecs.length
            ) {
              for (let i = 0; i < immIds.length; i++) {
                item.logImm.push({
                  id: immIds[i],
                  // productId: immProductIds[i],
                  name: immNames[i],
                  unit: immUnits[i],
                  amount: immAmounts[i],
                  spec: immSpecs[i]
                })
              }
            }
          }

          item.log_time = this.getSubstr(item.log_time)
          item.imm_product_name = this.getNewline(item.imm_product_name)
          item.imm_dosage = this.getNewline(item.imm_dosage)
          item.drug_product_name = this.getNewline(item.drug_product_name)
          item.drug_product_amount = this.getNewline(item.drug_product_amount)
          item.hasEgg = this.houseSelected.hasEgg
          return item
        })

        // 当前日志的时间（天）
        let currentLogDate = new Date()
        if (currentLogDate.getHours() < 12) {
          currentLogDate = new Date(currentLogDate.getTime() - 8.64e7)
        }
        this.currentLogDateStr = this.$utils.dateFormat(currentLogDate, logDateFormat)
        // currentLogDate = new Date(this.getDate(`${this.currentLogDateStr} 12:00:00`).getTime())

        if (!data.length) {
          return this.setLogs()
        }

        // 时间在7天内，按时间顺序，第一个用来判断是否是当天填写（当天12:00 ~ 次日12:00）
        // 是当天就修改，不是当天就添加
        const firstData = data[0]
        // 最后一次创建时间
        const logTime = this.$utils.dateFormat(firstData.log_time, logDateFormat)
        if (!logTime) { return }

        if (logTime === this.$utils.dateFormat(new Date(), logDateFormat)) {
          // 如里已经从其他地方（如：任务）中添加了今天的日志，当前日志时间就是今天（即使是在12点钟之前）
          this.currentLogDateStr = logTime
          this.setLogs(firstData)
        } else if (this.currentLogDateStr === logTime) {
          // 当前日志时间按12点来分，已经添加日志
          this.setLogs(firstData)
        } else {
          // 当前日志时间按12点来分，未添加日志
          this.setLogs()
        }
      }).catch(err => {
        this.setLogs()
        console.log(err)
      })
    },
    getSplit(str, splitor = ',') {
      return str ? str.split(splitor) : []
    },
    getDate(time, defaultDate = new Date()) {
      return time ? new Date(time.replace(/-/g, "/")) : defaultDate
    },
    getSubstr(str, start = 0, end = 10) {
      return str ? str.substr(start, end) : ''
    },
    getNewline(str, separator = ',') {
      return str ? str.replace(new RegExp(separator, 'g'), '\n') : ''
    },
    onSelectHouse(house, index) {
      this.houseIndex = index
      this.getBaseLog()
    },
    setLogs(data = {}) {
      this.houseSelected.currentLog = { ...data }
      this.currentBaseLog = { ...data }
      this.setBaseLog({ ...data })
    },
    setBaseLog(data) {
      Object.keys(this.baseLog).forEach(key => {
        let value = data[key] || ''
        if (!value) {
          if (key === 'logDrug' || key === 'logImm') { value = [] }
        }
        this.baseLog[key] = value
      })
    },
    selectLogTab(index) {
      this.logTabIndex = index
      this._animateTransformX(index)
    },
    goChickin() {
      this.$nav.open({
        name: 'farm.chickin'
      })
    },
    goHistory() {
      this.$nav.open({
        name: 'farm.chickin.history'
      })
    },
    onKeyboard(data) {
      console.log(data)
    },
    onInputFocus(val) {
      this.valueBefore = val
    },
    saveBaseLog(...args) {
      const noZero = ['feed_product_id', 'feed_product_name', 'feed_dosage_unit']
      const data = {}
      let hasChange = false
      let validNum = true
      for (const arg of args) {
        const val = this.baseLog[arg] || ''
        // 判断死鸡数与淘汰数不能太于存栏数
        if (validNum && (arg === 'die_num' || arg === 'eli_num')) {
          const num = +val || 0
          if (num > +this.houseSelected.current_amount) {
            validNum = false
            this.baseLog[arg] = this.valueBefore
          }
        }
        //
        if (val !== this.currentBaseLog[arg]) {
          hasChange = true
        }
        data[arg] = val || (noZero.includes(arg) ? '' : 0)
      }
      if (!validNum) {
        return this.$notice.toast({ message: '不能大于存栏数' })
      }
      if (this.currentBaseLog.base_produce_log_id) {
        if (hasChange) {
          this.putBaseLog(data)
        }
      } else {
        data.chick_house_enter_id = this.houseSelected.chick_house_enter_id
        data.log_type = this.isEggChick ? 1 : 2
        data.purchase_no = this.columnSelected.enter_batch_no
        data.log_time = this.currentLogDateStr
        // data.supplier_id = this.columnSelected.product_id
        this.postBaseLog(data)
      }
    },
    postBaseLog(data) {
      this.$api.addData({
        server: 'agr_chain',
        table: 'base_produce_log',
        data,
        errorMsg: '添加失败'
      }).then(res => {
        this.getHouseEnter(true)
        // this.$notice.toast({ message: '添加成功' })
      })
    },
    putBaseLog(data) {
      this.$api.updateData({
        server: 'agr_chain',
        table: 'base_produce_log',
        id: this.currentBaseLog.base_produce_log_id,
        data,
        errorMsg: '修改失败，请重试'
      }).then(res => {
        this.getHouseEnter(true)
        // this.$notice.toast({ message: '修改成功' })
      })
    },
    // 农资库存(全部获取，再分投料、免疫、用药)
    getStore() {
      this.$api.getData({
        server: 'agr_chain',
        table: 'goods_store_view',
        params: {
          'own_org_id.eq': this.farm.id
        }
      }).then(res => {
        const data = (res || []).map(item => {
          item.useAmount = undefined
          item.selected = false
          item.changeId = ''
          return item
        })
        this.forages = []
        this.drugs = []
        this.vaccines = []
        for (const item of data) {
          const id = item.goods_category_id
          if (!id) { continue }
          if (id.indexOf(CATEGORY_FORAGE) > -1) {
            this.forages.push(item)
          } else if (id.indexOf(CATEGORY_DRUG) > -1) {
            this.drugs.push(item)
          } else if (id.indexOf(CATEGORY_VACCINE) > -1) {
            this.vaccines.push(item)
          }
        }
      }).catch(err => {
        // this.$notice.toast({ message: '获取农资库存失败' })
      })
    },
    showForage() {
      this.forageVisible = true
    },
    onSelectForage(forage, index) {
      if (+forage.store_amount <= 0) {
        return this.$notice.toast({ message: '该投料类库存不足' })
      }
      this.forageIndex = index
      this.baseLog.feed_product_id = forage.goods_id
      this.baseLog.feed_product_name = forage.goods_name
      this.saveBaseLog('feed_product_id', 'feed_product_name')
      this.forageVisible = false
    },
    _animateTransformX(index) {
      const containerEl = this.$refs[`log-container`]
      if (!containerEl) { return }
      const dist = index * this.logContentWidth

      animation.transition(containerEl, {
        styles: {
          transform: `translateX(${-dist}px)`
        },
        duration: 200,
        timingFunction: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)',
        delay: 0
      }, () => { })

      const historyEl = this.$refs[`tab-history`]
      if (!historyEl) { return }
      animation.transition(historyEl, {
        styles: {
          transform: `translateX(${-dist}px)`
        },
        duration: 200,
        timingFunction: 'cubic-bezier(0.25, 0.46, 0.45, 0.94)',
        delay: 0
      }, () => { })
    },
    // 选择疫苗
    showVaccine() {
      // 设置默认值
      const immLog = this.houseSelected.currentLog.logImm || []
      const immObj = Object.create(null)
      for (const il of immLog) {
        immObj[il.spec] = {
          amount: il.amount,
          id: il.id
        }
      }
      for (const vaccine of this.vaccines) {
        const temp = immObj[vaccine.spec_id] || {}
        vaccine.useAmount = temp.amount || ''
        vaccine.changeId = temp.id || ''
        if (vaccine.changeId) {
          vaccine.selected = true
        }
      }

      this.vaccineVisible = true
    },
    hideVaccine() {
      this.$refs['vaccinePopup'].hide()
    },
    vaccineBeforeClose() {
      this.vaccineVisible = false
    },
    onVaccineSubmit() {
      const masterTable = {
        chick_house_enter_id: this.houseSelected.chick_house_enter_id
      }
      if (this.currentBaseLog.base_produce_log_id) {
        masterTable.base_produce_log_id = this.currentBaseLog.base_produce_log_id
      }
      const slaveData = []
      for (const vaccine of this.vaccines) {
        if (vaccine.selected && vaccine.useAmount) {
          const temp = {
            chick_house_enter_id: this.houseSelected.chick_house_enter_id,
            imm_amount: vaccine.useAmount,
            imm_product: vaccine.goods_id,
            imm_spec_id: vaccine.spec_id
          }
          if (vaccine.changeId) { temp.id = vaccine.changeId }
          slaveData.push(temp)
        }
      }
      // if (!slaveData.length) {
      //   return this.$notice.toast({ message: '至少填写一种疫苗' })
      // }
      const data = {
        masterTableInfo: JSON.stringify(masterTable),
        masterTableName: 'base_produce_log',
        slaveTableInfo: JSON.stringify(slaveData),
        slaveTableName: 'base_produce_log_imm'
      }
      if (this.currentBaseLog.base_produce_log_id) {
        this.$api.relatedUpdate({
          server: 'agr_chain',
          data,
          errorMsg: '日志提交失败，请重试'
        }).then(res => {
          this.hideVaccine()
          this.getHouseEnter(true)
        })
      } else {
        this.$api.relatedBatch({
          server: 'agr_chain',
          data,
          errorMsg: '日志提交失败，请重试'
        }).then(res => {
          this.hideVaccine()
          this.getHouseEnter(true)
        })
      }
    },
    toggleVaccine(row, index) {
      this.$set(row, 'selected', !row.selected)
    },
    onVaccineBlur(row, index) {
      if (row.useAmount) {
        const store = +row.store_amount || 0
        if (+row.useAmount > store) {
          this.$notice.toast({ message: '库存不足' })
          this.$set(row, 'useAmount', store)
        }
        this.$set(row, 'selected', true)
      } else {
        this.$set(row, 'selected', false)
      }
    },
    // 选择用药
    showDrug() {
      // 设置默认值
      const drugLog = this.houseSelected.currentLog.logDrug || []
      const drugObj = Object.create(null)
      for (const il of drugLog) {
        drugObj[il.spec] = {
          amount: il.amount,
          id: il.id
        }
      }
      for (const drug of this.drugs) {
        const temp = drugObj[drug.spec_id] || {}
        drug.useAmount = temp.amount || ''
        drug.changeId = temp.id || ''
        if (drug.changeId) {
          drug.selected = true
        }
      }

      this.drugVisible = true
    },
    hideDrug() {
      this.$refs['drugPopup'].hide()
    },
    drugBeforeClose() {
      this.drugVisible = false
    },
    onDrugSubmit() {
      const masterTable = {
        chick_house_enter_id: this.houseSelected.chick_house_enter_id
      }
      if (this.currentBaseLog.base_produce_log_id) {
        masterTable.base_produce_log_id = this.currentBaseLog.base_produce_log_id
      }
      const slaveData = []
      for (const drug of this.drugs) {
        if (drug.selected && drug.useAmount) {
          const temp = {
            chick_house_enter_id: this.houseSelected.chick_house_enter_id,
            drug_amount: drug.useAmount,
            drug_product: drug.goods_id,
            drug_spec_id: drug.spec_id
          }
          if (drug.changeId) { temp.id = drug.changeId }
          slaveData.push(temp)
        }
      }
      // if (!slaveData.length) {
      //   return this.$notice.toast({ message: '至少填写一种药品' })
      // }
      const data = {
        masterTableInfo: JSON.stringify(masterTable),
        masterTableName: 'base_produce_log',
        slaveTableInfo: JSON.stringify(slaveData),
        slaveTableName: 'base_produce_log_drug'
      }
      if (this.currentBaseLog.base_produce_log_id) {
        this.$api.relatedUpdate({
          server: 'agr_chain',
          data,
          errorMsg: '日志提交失败，请重试'
        }).then(res => {
          this.hideDrug()
          this.getHouseEnter(true)
        })
      } else {
        this.$api.relatedBatch({
          server: 'agr_chain',
          data,
          errorMsg: '日志提交失败，请重试'
        }).then(res => {
          this.hideDrug()
          this.getHouseEnter(true)
        })
      }
    },
    toggleDrug(row, index) {
      this.$set(row, 'selected', !row.selected)
    },
    onDrugBlur(row, index) {
      if (row.useAmount) {
        const store = +row.store_amount || 0
        if (+row.useAmount > store) {
          this.$notice.toast({ message: '库存不足' })
          this.$set(row, 'useAmount', store)
        }
        this.$set(row, 'selected', true)
      } else {
        this.$set(row, 'selected', false)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
@import "../../css/variables.scss";
$house-bg-active: lighten($primary, 40%);
$house-border-active: $primary;
$house-bg: lighten($info, 40%);
$house-border: lighten($info, 20%);

.icon {
  font-family: alicon;
}
.mt-1 {
  margin-top: 10px;
}
.mb-1 {
  margin-bottom: 10px;
}
.mb-2 {
  margin-bottom: 20px;
}
.mb-3 {
  margin-bottom: 30px;
}
.ml-0 {
  margin-left: 0px;
}
.ml-1 {
  margin-left: 10px;
}
.ml-2 {
  margin-left: 20px;
}
.mr-0 {
  margin-right: 0px;
}
.mr-1 {
  margin-right: 10px;
}
.mr-2 {
  margin-right: 20px;
}
.p-3 {
  padding: 30px;
}
.p-1 {
  padding: 10px;
}
.p-2 {
  padding: 20px;
}
.pt-2 {
  padding-top: 20px;
}
.px-2 {
  padding-left: 20px;
  padding-right: 20px;
}
.text-muted {
  color: #999;
}
.text-primary {
  color: $primary;
}
.text-info {
  color: $info;
}
.text-error {
  color: $error;
}
.text-warning {
  color: $warning;
}
.text-success {
  color: $success;
}
.text-white {
  color: #fff;
}
.text-center {
  text-align: center;
}
.text {
  font-size: 28px;
}
.bg-white {
  background-color: #fff;
}
.flex {
  flex: 1;
}
.flex-row {
  flex-direction: row;
  align-items: center;
}
.small {
  font-size: 26px;
}
.border-bottom {
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
}
.align-center {
  align-items: center;
}

.log-table-wrap {
  flex: 1;
  padding: 18px;
  border-width: 1px;
  border-color: lighten($primary, 40%);
  background-color: lighten($primary, 48%);
}
.log-border-head {
  border-top-width: 1px;
  border-top-color: $primary;
  // border-left-width: 1px;
  // border-left-color: $primary;
  // border-right-width: 1px;
  // border-right-color: $primary;
}

.td-row {
  width: 750px;
  flex-direction: row;
  align-items: center;
  padding-top: 25px;
  padding-bottom: 25px;
  background-color: #fff;
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
}
.td-row-active {
  background-color: $house-bg-active;
}
.td-row:active {
  background-color: #eee;
}
.td-text {
  flex: 1;
  text-align: center;
  font-size: 25px;
}
.td-serial {
  width: 80px;
  text-align: center;
  font-size: 25px;
}

.empty-text {
  padding: 30px;
  color: #999;
  background-color: #fff;
  text-align: center;
  font-size: 25px;
}

.house-title {
  padding-left: 20px;
  padding-right: 20px;
  padding-top: 20px;
  background-color: #fff;
  margin-top: 10px;
  flex-direction: row;
  align-items: center;
  border-top-width: 1px;
  border-top-color: $primary;
}
.house-wrap {
  background-color: #fff;
}
.house-scroller {
  flex-direction: row;
  width: 750px;
  height: 250px;
  margin-bottom: -1px;
  padding-left: 20px;
  padding-right: 20px;
}
.house {
  margin-left: 15px;
  margin-top: 15px;
  background-color: transparent;
  border-left-width: 2px;
  border-left-color: transparent;
  border-right-width: 2px;
  border-right-color: transparent;
  border-bottom-width: 2px;
  border-bottom-color: transparent;
}
.house-active {
  margin-left: 15px;
  margin-top: 15px;
  background-color: $house-bg-active;
  border-left-width: 2px;
  border-left-color: $house-border-active;
  border-right-width: 2px;
  border-right-color: $house-border-active;
  border-bottom-width: 2px;
  border-bottom-color: $house-bg-active;
}
.house-inner {
  height: 220px;
  padding: 20px;
  align-items: center;
  border-top-width: 2px;
  border-top-color: $house-border;
  border-bottom-width: 1px;
  border-bottom-color: $house-border;
  border-left-width: 1px;
  border-left-color: $house-border;
  border-right-width: 1px;
  border-right-color: $house-border;
  background-color: $house-bg;
}
.house-inner-active {
  height: 220px;
  padding: 20px;
  align-items: center;
  border-top-width: 2px;
  border-top-color: $house-border-active;
  border-bottom-width: 1px;
  border-bottom-color: transparent;
  border-left-width: 1px;
  border-left-color: transparent;
  border-right-width: 1px;
  border-right-color: transparent;
  background-color: $house-bg-active;
}
.house-no {
  padding-left: 50px;
  padding-right: 50px;
  padding-top: 10px;
  padding-bottom: 20px;
  text-align: center;
  color: $info;
  font-size: 32px;
}
.house-status {
  font-size: 28px;
  margin-bottom: 6px;
}
.house-status-all {
  padding-top: 25px;
}
.house-next {
  position: absolute;
  top: 0px;
  right: 0px;
  bottom: 0px;
  line-height: 250px;
  color: #999;
  background-image: linear-gradient(to left, #fff, rgba(255, 255, 255, 0.2));
}
.house-bottom {
  position: absolute;
  left: 0px;
  right: 0px;
  bottom: 0px;
  height: 1px;
  border-bottom-width: 2px;
  border-bottom-color: $house-border-active;
}

.house-log {
  background-color: $house-bg-active;
  padding-top: 20px;
  padding-bottom: 10px;
}

.log-tab {
  flex-direction: row;
  border-bottom-width: 1px;
  border-bottom-color: $primary;
}
.log-tab-text {
  padding: 20px;
  flex: 1;
  text-align: center;
  font-size: 28px;
  margin-left: 2px;
  margin-right: 2px;
  margin-bottom: -1px;
  border-top-width: 1px;
  border-top-color: $primary;
  border-left-width: 1px;
  border-left-color: $primary;
  border-right-width: 1px;
  border-right-color: $primary;
  background-color: #fff;
}
.log-tab-text-inactive {
  color: #666;
  border-bottom-width: 1px;
  border-bottom-color: $primary;
  background-color: #f6f6f6;
}
.log-tab-text-active {
  border-bottom-width: 1px;
  border-bottom-color: #fff;
}

.container {
  width: 750px;
}
.tab-container {
  flex: 1;
  flex-direction: row;
  align-items: stretch;
}
.tab-content {
  flex: 1;
}

.log-container {
  flex: 1;
  flex-direction: row;
  align-items: stretch;
}
.log-content {
  flex: 1;
  background-color: #fff;
  padding: 20px;
  border-bottom-width: 1px;
  border-bottom-color: $primary;
  min-height: 280px;
  // border-left-width: 1px;
  // border-left-color: $primary;
  // border-right-width: 1px;
  // border-right-color: $primary;
  // margin-right: 1px;
}

.input {
  flex: 1;
  border-width: 1px;
  border-color: $border-color;
  height: 60px;
  line-height: 60px;
  font-size: 26px;
  padding-left: 10px;
  padding-right: 10px;
  tint-color: #999;
}
.label-text {
  font-size: 26px;
  color: #666;
  margin-right: 10px;
}
.unit-text {
  font-size: 26px;
  background-color: $border-color;
  height: 60px;
  line-height: 60px;
  padding-left: 10px;
  padding-right: 10px;
  text-align: center;
  color: #666;
}

.log-status {
  padding-top: 2px;
  padding-bottom: 2px;
  padding-left: 15px;
  padding-right: 15px;
  border-radius: 20px;
  font-size: 20px;
  color: #fff;
}
.log-status-success {
  background-color: $success;
}
.log-status-warning {
  background-color: $warning;
}

.select {
  flex: 1;
  border-width: 1px;
  border-color: $border-color;
  height: 60px;
  line-height: 60px;
  font-size: 26px;
  padding-left: 10px;
  padding-right: 10px;
}
.select-text {
  color: #333;
}
.select-placeholder {
  color: #999;
}

.list-text {
  padding: 30px;
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
}
.list-text-active {
  color: $primary;
}

.btn {
  width: 300px;
  height: 70px;
  line-height: 70px;
  border-radius: 35px;
  padding-left: 30px;
  padding-right: 30px;
  text-align: center;
  font-size: 28px;
  border-width: 1px;
  border-color: #ddd;
  margin-top: 20px;
  margin-bottom: 20px;
}
.btn:active {
  background-color: #ddd;
}
.popup-btns {
  padding: 10px;
  border-top-width: 1px;
  border-top-color: #ddd;
}
.popup-btn-border {
  flex: 1;
  flex-direction: row;
  border-radius: 40px;
  border-width: 1px;
  border-color: $primary;
}
.popup-btn {
  flex: 1;
  padding: 16px;
  color: $primary;
}
.popup-btn-dismiss {
  border-top-left-radius: 40px;
  border-bottom-left-radius: 40px;
  background-color: lighten($primary, 45%);
}
.popup-btn-confirm {
  border-top-right-radius: 40px;
  border-bottom-right-radius: 40px;
  background-color: lighten($primary, 15%);
}
.popup-btn:active {
  background-color: lighten($primary, 35%);
}
.popup-btn-text {
  text-align: center;
}
</style>
